from model import model
from hashlib import sha1
from log import log
from utils import jwt
from schema import Schema


class adminDao():
    #创建管理员
    def createAdmin(self,user, passwd):
        try:
            admins = model.admin()
            admins.user = user
            admins.level = 1024
            admins.passwd = sha1(passwd.encode()).digest().hex()
            admins.save()
        except IOError:
            log.error(IOError)
            return False
        else:
            return True

    #检查用户登陆
    @staticmethod
    def checkAdmin(user, passwd):
        passwd = sha1(passwd.encode()).digest().hex()
        adminss = model.admin.objects(user=user, passwd=passwd)
        if len(adminss) == 1:
            return adminss.get()
        else:
            return False

    #解析jwt
    @staticmethod
    def checkAdminForJwt(id,user):
        try:
            adminss = model.admin.objects(user=user, id=id)
            if len(adminss) > 0 :
                return True
            else:
                return False
        except Exception:
            return False

    #验证jwt
    @staticmethod
    def checkJwt(jwtstr=None):
        if Schema(str).validate(jwtstr):
            try:
                admindisc = jwt.Jwt.checkJwt(jwtstr)
                if not admindisc == None:
                    return adminDao.checkAdminForJwt(admindisc["id"],admindisc["name"])
                else:
                    return False
            except Exception :
                return False
        else:
            return False
